package Demo84;

import java.util.LinkedList;
import java.util.Queue;

class Solution1 {
    int[] dx = new int[] {0,0,1,-1};
    int[] dy = new int[] {1,-1,0,0};

    char[][] grid;
    int m, n;
    public int numIslands(char[][] grid) {
        this.grid = grid;
        m = grid.length; n = grid[0].length;
        int ret = 0;

        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(grid[i][j] == '1') {
                    numIslands(i,j);
                    ret++;
                }
            }
        }
        return ret;
    }

    private void numIslands(int i, int j) {
        Queue<int[]> q = new LinkedList<>();
        q.add(new int[] {i,j});
        grid[i][j] = '0';

        while(!q.isEmpty()) {
            int[] t = q.poll();
            int a = t[0], b = t[1];

            for(int k = 0; k < 4; k++) {
                int x = a + dx[k], y = b + dy[k];
                if(x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == '1') {
                    q.add(new int[] {x, y});
                    grid[x][y] = '0';
                }
            }
        }
    }
}
class Demo1 {
    public static void main(String[] args) {
        Solution1 solution = new Solution1();
        int ret = solution.numIslands(new char[][]{{'1', '1', '0', '0', '0'}, {'1', '1', '0', '0', '0'}, {'0', '0', '1', '0', '0'}, {'0', '0', '0', '1', '1'}});
        System.out.println(ret);
    }
}

